package com.simple.dispatcher.service;


import javax.annotation.PostConstruct;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;

import weibo4j.Weibo;
import weibo4j.http.AccessToken;
import weibo4j.http.RequestToken;

@Service
public class WeiboOAuthService {
	
	private final Log log = LogFactory.getLog(getClass());

	public WeiboOAuthService() {
	}
	
	@PostConstruct
	public void init() {
	}

	// 根据传入的 callback_url 获取 request token
	public RequestToken getRequestToken(String backUrl) {
		try {
			Weibo weibo = new Weibo();
			// 指定 callback_url 并获得 request token
			RequestToken requestToken = weibo.getOAuthRequestToken(backUrl);
			log.debug("RequestToken: " + requestToken.getToken()
					+ ", RequestTokenSecret: " + requestToken.getTokenSecret());
			return requestToken;
		} catch (Exception e) {
			log.error("获取Request token失败！");
			e.printStackTrace();
			return null;
		}
	}

	// 根据传入的 request token 和 verifier 获取 access token
	public AccessToken gettAccessToken(RequestToken requestToken,
			String verifier) {
		try {
			Weibo weibo = new Weibo();
			AccessToken accessToken = weibo.getOAuthAccessToken(requestToken
					.getToken(), requestToken.getTokenSecret(), verifier);

			log.debug("UserId: " + accessToken.getUserId() + ", AccessToken: " + accessToken.getToken()
					+ ", AccessTokenSecret: "	+ accessToken.getTokenSecret() );
			return accessToken;
		} catch (Exception e) {
			log.error("获取Access token失败！");
			e.printStackTrace();
			return null;
		}
	}
}